var GCore = {
	ajaxDone:function(json){
		if(json["result"] == "error") {
			if(json["message"] && alertMsg) alertMsg.error(json["message"]);
		} else if (json["result"] == "timeout") {
			if(alertMsg) alertMsg.error(json["message"] || GCore.msg("sessionTimout"), {okCall:GCore.loadLogin});
			else GCore.loadLogin();
		} else if (json["result"] == "success"){
			if(json["message"] && alertMsg) alertMsg.success(json["message"]);
		};
	},
	ajaxError:function(xhr, ajaxOptions, thrownError){
		if (alertMsg) {
			alertMsg.error("<div>Http status: " + xhr.status + " " + xhr.statusText + "</div>" 
				+ "<div>ajaxOptions: "+ajaxOptions + "</div>"
				+ "<div>thrownError: "+thrownError + "</div>"
				+ "<div>"+xhr.responseText+"</div>");
		} else {
			alert("Http status: " + xhr.status + " " + xhr.statusText + "\najaxOptions: " + ajaxOptions + "\nthrownError:"+thrownError + "\n" +xhr.responseText);
		}
	},
	_msg:{"validateFormError":"{0}个项目有错误，请改正后再提交!"
		,"sessionTimout":"会话超时，请重新登录!"
		,"statusCode_503":"服务器当前负载过大或者正在维护!"
		,"alertSelectMsg":"请选择数据!"}, //alert message
	msg:function(key, args){
		var _format = function(str,args) {
			args = args || [];
			var result = str || "";
			for (var i = 0; i < args.length; i++){
				result = result.replace(new RegExp("\\{" + i + "\\}", "g"), args[i]);
			}
			return result;
		};
		return _format(this._msg[key], args);
	},
	loadLogin:function(){
		if (GCore._set.loginTitle) {
			$.pdialog.open(GCore._set.loginUrl, "login", GCore._set.loginTitle, {mask:true,width:520,height:260});
		} else {
			window.location = GCore._set.loginUrl;
		}
	},
	jsonEval:function(data) {
		try{
			if ($.type(data) == 'string')
				return eval('(' + data + ')');
			else return data;
		} catch (e){
			return {};
		}
	}
}

var alertMsg = {
		error: function(msg) {
			layer.alert(msg,{icon:2});
		},
		success: function(msg) {
			layer.msg(msg,{icon:1});
		},
		confirm: function(msg,options) {
			layer.confirm(msg, {
				btn: ['确定','取消'] //按钮
			},
			options.okCall,
			function(){
				//不处理
			});
		}
};
function dialogAjaxDone(json){
	GCore.ajaxDone(json);
	if (json["result"] == "success"){
		if (json["refreshParent"]){
			parent.bootstrapTableRefresh();
		}
		if(json["callbackType"]=="closeCurrent") {
			parent.alertMsg.success(json.message);
			var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
			parent.layer.close(index);
		}
	}
}

function reloadAjaxDone(json){
	GCore.ajaxDone(json);
	location.reload();
}

function pageAjaxDone(json){
	if(json["result"] == "error") {
		if(json["message"] && alertMsg) alertMsg.error(json["message"]);
	} else if (json["result"] == "timeout") {
		if(alertMsg) alertMsg.error(json["message"] || GCore.msg("sessionTimout"), {okCall:GCore.loadLogin});
		else GCore.loadLogin();
	} else if (json["result"] == "success"){
		if(json["redirect"] && json["message"]){
			layer.confirm(json["message"], {
				btn: ['返回','继续'] //按钮
			},function(){
				location.href=json["redirect"];
			},function(){
				location.reload();
			});
		}else {
			if(json["message"] && alertMsg) alertMsg.success(json["message"]);
		}
	};
}

function navTabAjaxDone(json){
	GCore.ajaxDone(json);
	if (json["result"] == "success"){
		if (json["refreshParent"]){
			bootstrapTableRefresh();
		}
	}
}

function ajaxTodoAjaxDone(json){
	GCore.ajaxDone(json);
	if (json["result"] == "success"){
		bootstrapTableRefresh();
	}
}


/**
 * 带文件上传的ajax表单提交
 * @param {Object} form
 * @param {Object} callback
 */
function iframeCallback(form, callback){
	var $form = $(form), $iframe = $("#callbackframe");
	if(!$form.valid()) {return false;}

	if ($iframe.size() == 0) {
		$iframe = $("<iframe id='callbackframe' name='callbackframe' src='about:blank' style='display:none'></iframe>").appendTo("body");
	}
	if(!form.ajax) {
		$form.append('<input type="hidden" name="ajax" value="1" />');
	}
	form.target = "callbackframe";
	
	_iframeResponse($iframe[0], callback || ZT.ajaxDone);
}
function _iframeResponse(iframe, callback){
	var $iframe = $(iframe), $document = $(document);

	$document.trigger("ajaxStart");
	$iframe.bind("load", function(event){
		$iframe.unbind("load");

		$document.trigger("ajaxStop");
		if (iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For Safari
			iframe.src == "javascript:'<html></html>';") { // For FF, IE
			return;
		}

		var doc = iframe.contentDocument || iframe.document;

		// fixing Opera 9.26,10.00
		if (doc.readyState && doc.readyState != 'complete') return; 
		// fixing Opera 9.64
		if (doc.body && doc.body.innerHTML == "false") return;
	   
		var response;
		
		if (doc.XMLDocument) {
			// response is a xml document Internet Explorer property
			response = doc.XMLDocument;
		} else if (doc.body){
			try{
				response = $iframe.contents().find("body").text();
				response = jQuery.parseJSON(response);
			} catch (e){ // response is html document or plain text
				response = doc.body.innerHTML;
			}
		} else {
			// response is a xml document
			response = doc;
		}
		
		callback(response);
	});
}

/**
 * 普通ajax表单提交
 * @param {Object} form
 * @param {Object} callback
 * @param {String} confirmMsg 提示确认信息
 */
function validateCallback(form, callback, confirmMsg) {
	var $form = $(form);

	if (!$form.valid()) {
		return false;
	}
	
	var _submitFn = function(){
		$.ajax({
			type: form.method || 'POST',
			url:$form.attr("action"),
			data:$form.serializeArray(),
			dataType:"json",
			cache: false,
			success: callback || GCore.ajaxDone,
			error: GCore.ajaxError
		});
	};
	
	if (confirmMsg) {
		alertMsg.confirm(confirmMsg, {okCall: _submitFn});
	} else {
		_submitFn();
	}
	
	return false;
}
function ajaxTodo(url, callback){
	var $callback = callback || ajaxTodoAjaxDone;
	if (! $.isFunction($callback)) $callback = eval('(' + callback + ')');
	$.ajax({
		type:'POST',
		url:url,
		dataType:"json",
		cache: false,
		success: $callback,
		error: GCore.ajaxError
	});
}

function ajaxTodoByConfirm(url,confirm,callback){	
	if (confirm) {
		alertMsg.confirm(confirm, {
			okCall: function(){
				ajaxTodo(url, callback);
			}
		});
	} else {
		ajaxTodo(url, callback);
	}
}

var ajaxLoadIndex;
function initUI(_box){
	$(document).ajaxStart(function(){
		ajaxLoadIndex = layer.load(0, {shade: false}); 
	}).ajaxStop(function(){
		layer.close(ajaxLoadIndex);
	});
	
	var $p = $(_box || document);
	if ($.fn.selectedTodo) $("a[target=selectedTodo]", $p).selectedTodo();
	//validate form
	$("form.required-validate", $p).each(function(){
		var $form = $(this);
		$form.find("input").each(function(){
			var $this = $(this);
			if($this.attr("name")&&typeof($this.attr("id"))=="undefined"){
				$this.attr("id",$this.attr("name").replace(".","_"));
			}
		});
		$form.validate({
			onsubmit: false,
			focusInvalid: false,
			focusCleanup: true,
			ignore:".ignore"
		});
	});
	//需bootstrapTable插件支持
	if ($.fn.bootstrapTable){
		$("#bootstrapTable", $p).each(function(){
			var $table = $(this);
			$table.bootstrapTable({
				striped:true,
				height:$(window).height(),
				pagination:true,
				sidePagination:"server",
				cache:false,
				pageSize:20,
				pageList:[10, 20, 50, 100, 200, 500,1000],
				toolbar:"#toolbar",
				showColumns:true,
				showRefresh:true,
				iconSize:"outline",
				queryParamsType:"long",
				queryParams:function(params){
					if($("#AdvanceSearch").size()>0) {
			            $.each($("#AdvanceSearch form").serializeJson(),function(index,item){
			            	params[index] = item;
			            });
					}
					params["is_ajax"]="T";
					return params;
				}
			});
			$(window).resize(function () {
				$table.bootstrapTable('resetView', {
					height: $(window).height()
		      });
		    });
		});
	}

	//ajaxTodo
	if ($.fn.ajaxTodo) $("a[target=ajaxTodo]", $p).ajaxTodo();
}
function xuhaoFormatter(value,row,index){
	var options = $('#bootstrapTable').bootstrapTable('getOptions');
	var page = options.pageNumber;
	var pagesize = options.pageSize;
	return (page-1)*pagesize+index+1;
}
function timeToDateFormatter(value,row,index){
	if(value){
		return value.substring(0,10);
	}
}
//bootstrapTable插件扩展函数
function bootstrapTableRefresh(){
	var params = $("#AdvanceSearch form").serializeJson();
	params["pageNumber"] = 1;
	$("#bootstrapTable").bootstrapTable("refresh",{query:params});
	return false;
}

$().ready(function() {
	initUI(document); 
});

(function($){  
	//扩展serializeJson
    $.fn.serializeJson=function(){  
        var serializeObj={};  
        $(this.serializeArray()).each(function(){  
            serializeObj[this.name]=this.value;  
        });  
        return serializeObj;  
    };  

    //扩展validator
	if ($.validator) {
		$.validator.addMethod("alphanumeric", function(value, element) {
			return this.optional(element) || /^\w+$/i.test(value);
		}, "Letters, numbers or underscores only please");
		
		$.validator.addMethod("lettersonly", function(value, element) {
			return this.optional(element) || /^[a-z]+$/i.test(value);
		}, "Letters only please"); 
		
		$.validator.addMethod("phone", function(value, element) {
			return this.optional(element) || /^[0-9 \(\)]{7,30}$/.test(value);
		}, "Please specify a valid phone number");
		
		$.validator.addMethod("postcode", function(value, element) {
			return this.optional(element) || /^[0-9 A-Za-z]{5,20}$/.test(value);
		}, "Please specify a valid postcode");
		
		$.validator.addMethod("date", function(value, element) {
			value = value.replace(/\s+/g, "");
			if (String.prototype.parseDate){
				var $input = $(element);
				var pattern = $input.attr('dateFmt') || 'yyyy-MM-dd';
	
				return !$input.val() || $input.val().parseDate(pattern);
			} else {
				return this.optional(element) || value.match(/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/);
			}
		}, "Please enter a valid date.");
		
		/*自定义js函数验证
		 * <input type="text" name="xxx" customvalid="xxxFn(element)" title="xxx" />
		 */
		$.validator.addMethod("customvalid", function(value, element, params) {
			try{
				return eval('(' + params + ')');
			}catch(e){
				return false;
			}
		}, "Please fix this field.");
		
		$.validator.addClassRules({
			date: {date: true},
			alphanumeric: { alphanumeric: true },
			lettersonly: { lettersonly: true },
			phone: { phone: true },
			postcode: {postcode: true}
		});
		$.validator.setDefaults({errorElement:"span"});
		$.validator.autoCreateRanges = true;
	}
    
	
	$.fn.extend({
		ajaxTodo:function(){
			return this.each(function(){
				var $this = $(this);
				$this.click(function(event){
					var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
					
					if (!url.isFinishedTm()) {
						alertMsg.error($this.attr("warn") || GCore.msg("alertSelectMsg"));
						return false;
					}
					var title = $this.attr("title");
					if (title) {
						alertMsg.confirm(title, {
							okCall: function(){
								ajaxTodo(url, $this.attr("callback"));
							}
						});
					} else {
						ajaxTodo(url, $this.attr("callback"));
					}
					event.preventDefault();
				});
			});
		},
		/**
		 * @param {Object} op: {type:GET/POST, url:ajax请求地址, data:ajax请求参数列表, callback:回调函数 }
		 */
		ajaxUrl: function(op){
			var $this = $(this);

			//$this.trigger(ZT.eventType.pageClear);
			
			$.ajax({
				type: op.type || 'GET',
				url: op.url,
				data: op.data,
				cache: false,
				success: function(response){
					var json = GCore.jsonEval(response);
					
					if (json["result"]=="error"){
						if (json["message"]) alertMsg.error(json["message"]);
					} else {
						//$this.html(response).initUI();
						$this.html(response);
						if ($.isFunction(op.callback)) op.callback(response);
					}
					
					if (json["result"]=="timeout"){
						//if ($.pdialog) $.pdialog.checkTimeout();
						//if (navTab) navTab.checkTimeout();
						alertMsg.error(json["message"] || GCore.msg("sessionTimout"), {okCall:function(){
							GCore.loadLogin();
						}});
					} 
					
				},
				error: GCore.ajaxError,
				statusCode: {
					503: function(xhr, ajaxOptions, thrownError) {
						alert(GCore.msg("statusCode_503") || thrownError);
					}
				}
			});
		},
		loadUrl: function(url,data,callback){
			$(this).ajaxUrl({url:url, data:data, callback:callback});
		},
		initUI: function(){
			return this.each(function(){
				if($.isFunction(initUI)) initUI(this);
			});
		},
		selectedTodo: function(){
			function _getIds(selectedIds, targetType){
				var ids = "";
				$("input:checked").filter("[name='"+selectedIds+"']").each(function(i){
					var val = $(this).val();
					ids += i==0 ? val : ","+val;
				});
				return ids;
			}
			return this.each(function(){
				var $this = $(this);
				var selectedIds = $this.attr("rel") || "ids";
				var postType = $this.attr("postType") || "map";
	
				$this.click(function(){
					var targetType = $this.attr("targetType");
					var ids = _getIds(selectedIds, targetType);
					if (!ids) {
						alertMsg.error($this.attr("warn") || GCore.msg("alertSelectMsg"));
						return false;
					}
					
					var _callback = $this.attr("callback") || (targetType == "dialog" ? dialogAjaxDone : navTabAjaxDone);
					if (! $.isFunction(_callback)) _callback = eval('(' + _callback + ')');
					
					function _doPost(){
						$.ajax({
							type:'POST', url:$this.attr('href'), dataType:'json', cache: false,
							data: function(){
								if (postType == 'map'){
									return $.map(ids.split(','), function(val, i) {
										return {name: selectedIds, value: val};
									})
								} else {
									var _data = {};
									_data[selectedIds] = ids;
									return _data;
								}
							}(),
							success: _callback,
							error: GCore.ajaxError
						});
					}
					var title = $this.attr("title");
					if (title) {
						alertMsg.confirm(title, {okCall: _doPost});
					} else {
						_doPost();
					}
					return false;
				});
				
			});
		}
	});
	
	/**
	 * 扩展String方法
	 */
	$.extend(String.prototype, {
		replaceTmById:function(_box){
			var $parent = _box || $(document);
			return this.replace(RegExp("({[A-Za-z_]+[A-Za-z0-9_]*})","g"), function($1){
				var $input = $parent.find("#"+$1.replace(/[{}]+/g, ""));
				return $input.val() ? $input.val() : $1;
			});
		},
		isFinishedTm:function(){
			return !(new RegExp("{[A-Za-z_]+[A-Za-z0-9_]*}").test(this)); 
		}
	});
})(jQuery); 